package com.huaxin.hxcloud.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.media.view.PhotoAddView;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.find.view.adapter.ImagePickerAdapter;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 意见反馈
 */
public class FeedBackActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, ImagePickerAdapter.OnRecyclerViewItemClickListener, ImagePickerAdapter.OnDeleteItemClickListener {


    @BindView(R.id.more)
    TextView     more;
    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.rb_feedback_error)
    RadioButton  rbFeedbackError;
    @BindView(R.id.rb_feedback_function)
    RadioButton  rbFeedbackFunction;
    @BindView(R.id.et_feedback)
    EditText     etFeedback;
    @BindView(R.id.tv_contact)
    TextView     tvContact;
    @BindView(R.id.rl_img)
    PhotoAddView rlImg;
    @BindView(R.id.rg_feedback)
    RadioGroup   rgFeedback;
    private int type = 0;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    //选中数量限制
    private int maxImgCount = 4;
    private ArrayList<ImageItem> mSelImageList;
    public static final int IMAGE_ITEM_ADD       = -1;
    public static final int REQUEST_CODE_SELECT  = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private ImagePickerAdapter mImagePickerAdapter;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_feedback;
    }

    @Override
    public void initView() {
        super.initView();
        setSupportActionBar(toolbar);
        toolbar.setTitle(R.string.user_feedback);
        more.setText(R.string.submit);
        rgFeedback.setOnCheckedChangeListener(this);
        ImagePicker picker = BaseApp.getImagePicker();
        if (picker != null) {
            picker.setSelectLimit(maxImgCount);
        }
    }

    @Override
    public void initData() {
        super.initData();
        mSelImageList = new ArrayList<>();
        mImagePickerAdapter = new ImagePickerAdapter(this, mSelImageList, maxImgCount);
        mImagePickerAdapter.setOnItemClickListener(this);
        mImagePickerAdapter.setDeleteItemClickListener(this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mImagePickerAdapter);
    }

    @OnClick({R.id.more})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.more:
                hideIme();
                submitForm();
                break;
            default:
                break;
        }

    }

    //隐藏键盘
    private void hideIme() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context
                .INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive(etFeedback)) {
            imm.hideSoftInputFromWindow(etFeedback.getWindowToken(), 0);
        }
    }

    private void submitForm() {

        List<String> imageDatas = new ArrayList<>();
        for (int i = 0; i < mSelImageList.size(); i++) {
            String path = mSelImageList.get(i).path;
            imageDatas.add(path);
        }

        final Dialog dialog = DialogUtil.getWaitDialog(this, "提交中");
        dialog.show();
        Call<BaseDTO> call = RequestHelper.getRequestApi().addSuggestion(type, etFeedback.getText().toString(), RequestHelper.createFileParts(imageDatas.toArray(new String[imageDatas.size()])));
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        ToastUtil.showToast(baseDTO.getMsg());
                        finish();
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.submit_faile));
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast(getString(R.string.network_faile));
            }
        });
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_feedback_error:
                type = 0;
                break;
            case R.id.rb_feedback_function:
                type = 1;
                break;
            default:
                break;

        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    mSelImageList.clear();
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        }
    }

    @Override
    public void onDeleteItemClick(int position) {
        if (mSelImageList.size() > 0) {
            mSelImageList.remove(position);
            mImagePickerAdapter.setImages(mSelImageList);
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - mSelImageList.size());
                Intent intent1 = new Intent(FeedBackActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
                //                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) mImagePickerAdapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }
}
